package cn.easier.activity.console.service.impl;

import cn.easier.activity.console.entity.ActivityConsoleUser;
import cn.easier.activity.console.entity.ActivityMessages;
import cn.easier.activity.console.repository.*;
import cn.easier.activity.console.service.ActivityConsoleService;
import cn.easier.activity.web.dto.DailyMessageDto;
import cn.easier.activity.web.dto.QuestionnaireMessageDto;
import cn.easier.activity.web.entity.*;
import cn.easier.club.base.dto.ResultInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 活动留言ServiceImpl
 */
@Service
@Transactional
public class ActivityConsoleServiceImpl implements ActivityConsoleService {

    private final ActivityMessageRepository activityMessageRepository;
    private final QuestionnaireMessageRepository questionnaireMessageRepository;
    private final OptionMessageRepository optionMessageRepository;
    private final ActivityInfoRepository activityInfoRepository;
    private final ActivityRuleRepository activityRuleRepository;
    private final QuestionnaireAnswersMessageRepository questionnaireAnswersMessageRepository;

    public ActivityConsoleServiceImpl(ActivityMessageRepository activityMessageRepository, QuestionnaireMessageRepository questionnaireMessageRepository, OptionMessageRepository optionMessageRepository, ActivityInfoRepository activityInfoRepository, ActivityRuleRepository activityRuleRepository, QuestionnaireAnswersMessageRepository questionnaireAnswersMessageRepository) {
        this.activityMessageRepository = activityMessageRepository;
        this.questionnaireMessageRepository = questionnaireMessageRepository;
        this.optionMessageRepository = optionMessageRepository;
        this.activityInfoRepository = activityInfoRepository;
        this.activityRuleRepository = activityRuleRepository;
        this.questionnaireAnswersMessageRepository = questionnaireAnswersMessageRepository;
    }

    @Override
    public List<Object> getMessage(Integer activityId, String beginTime, String endTime, int pageNum, int pageSize) {
        int pageCount = pageNum * pageSize;
        String messageTimeStart = null;
        String messageTimeEnd = null;
        List<ActivityMessages> allBy = new ArrayList<>();
        long allByCount = 0L;
        if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            messageTimeStart = beginTime.substring(0, 10) + " 00:00:00 ";
            messageTimeEnd = endTime.substring(0, 10) + " 23:59:59 ";
        }
        ActivityConsoleUser principal = this.getPrincipal();
        String authoritiesStr = principal.getAuthoritiesStr();
        if (authoritiesStr.equals("ROLE_USER_SELF")) {
            String username = principal.getUsername();
            List<ActivityInfo> byCreateBy = activityInfoRepository.findByCreateByAndCreateTime(username);
            List<Integer> idList = new ArrayList<>();
            for (ActivityInfo activityInfo : byCreateBy) {
                idList.add(activityInfo.getId());
            }
            allBy = activityMessageRepository.findAllByUser(activityId, idList, messageTimeStart, messageTimeEnd, pageCount, pageSize);
            allByCount = activityMessageRepository.findAllByCountAndUser(activityId, idList, messageTimeStart, messageTimeEnd);
        } else {
            allBy = activityMessageRepository.findAllBy(activityId, messageTimeStart, messageTimeEnd, pageCount, pageSize);
            allByCount = activityMessageRepository.findAllByCount(activityId, messageTimeStart, messageTimeEnd);
        }
        List<Object> returnList = new ArrayList<>(allBy);
        returnList.add(allByCount);
        return returnList;
    }

    @Override
    public ResultInfo showMessage(Long id, String type) {
        Optional<ActivityMessages> byId = activityMessageRepository.findById(id);
        if (byId.isPresent()) {
            ActivityMessages activityMessage = byId.get();
            if (type.equals("1")) {
                activityMessage.setIsShow(1);
                activityMessageRepository.save(activityMessage);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "设置已显示成功", null);
            }
            if (type.equals("0")) {
                activityMessage.setIsShow(0);
                activityMessageRepository.save(activityMessage);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "设置未显示成功", null);
            }
        }
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "未查询到该留言信息", null);
    }

    @Override
    public ResultInfo getActivityName() {
        List<ActivityInfo> allActivityName = new ArrayList<>();
        ActivityConsoleUser principal = this.getPrincipal();
        String authoritiesStr = principal.getAuthoritiesStr();
        if (authoritiesStr.equals("ROLE_USER_SELF")) {
            String username = principal.getUsername();
            allActivityName = activityInfoRepository.findByTypeIdentificationAndCreateByAndStatusNotOrderByCreateTimeDesc("questionnaire", username, 2);
        } else {
            allActivityName = activityInfoRepository.findByTypeIdentificationAndStatusNotOrderByCreateTimeDesc("questionnaire", 2);
        }
        return new ResultInfo("SUCCESS", "查询活动名称成功", allActivityName);
    }

    @Override
    public ResultInfo delMessage(String type, Long id) {
        if (type == null) {
            OptionMessage byIdAndIsDel = optionMessageRepository.findByIdAndIsDel(id, 0);
            if (byIdAndIsDel == null) {
                return new ResultInfo("ERROR", "未查询到该选项信息", null);
            }
            byIdAndIsDel.setIsDel(1);
            optionMessageRepository.save(byIdAndIsDel);
            return new ResultInfo("SUCCESS", "删除成功", null);
        }
        if (type.equals("questionnaire")) {
            QuestionnaireMessage byIdAndIsDel = questionnaireMessageRepository.findByIdAndIsDel(id, 0);
            if (byIdAndIsDel == null) {
                return new ResultInfo("ERROR", "未查询到该题目信息", null);
            }
            byIdAndIsDel.setIsDel(1);
            questionnaireMessageRepository.save(byIdAndIsDel);
            return new ResultInfo("SUCCESS", "删除成功", null);
        }
        return new ResultInfo("ERROR", "删除失败", null);
    }

    @Override
    public ResultInfo questionnaireMessage(List<QuestionnaireMessageDto> params, Integer activityInfoId) {
        Optional<ActivityInfo> activityInfoOptional = activityInfoRepository.findById(activityInfoId);
        List<QuestionnaireMessageDto> questionnaireParams = new ArrayList<>();
        if (!activityInfoOptional.get().getTypeIdentification().equals("investigation")) {
            List<QuestionnaireMessage> byIsDelAndActivityInfoId = questionnaireMessageRepository.findByIsDelAndActivityInfoId(0, activityInfoId);
            if (CollectionUtils.isNotEmpty(byIsDelAndActivityInfoId)) {
                for (QuestionnaireMessage questionnaireMessage : byIsDelAndActivityInfoId) {
                    questionnaireMessage.setIsDel(1);
                    questionnaireMessageRepository.save(questionnaireMessage);
                }
            }
        }else {
            for (QuestionnaireMessageDto questionnaireMessageDto : params){
                if (questionnaireMessageDto.getId() == null){
                    questionnaireParams.add(questionnaireMessageDto);
                }
            }
            params.clear();
            params.addAll(questionnaireParams);
        }
        activityInfoOptional.ifPresent(activityInfo -> {
            for (QuestionnaireMessageDto questionnaireMessageDto : params) {
                QuestionnaireMessage q = new QuestionnaireMessage();
                q.setCreateTime(new Date());
                q.setIsDel(0);
                q.setIsSingle(questionnaireMessageDto.getIsSingle());
                q.setMustAnswer(questionnaireMessageDto.getMustAnswer());
                q.setQuestionnaireName(questionnaireMessageDto.getQuestionnaireName());
                q.setIsRandom(questionnaireMessageDto.getIsRandom());
                q.setActivityInfoId(activityInfoId);
                q.setYesterdayShow(0);
                q.setType(activityInfo.getTypeIdentification());
                q.setIsShow(0);
                List<OptionMessage> optionMessageList = questionnaireMessageDto.getOptionMessageList();
                if (questionnaireMessageDto.getIsRandom() == 1) {
                    Collections.shuffle(optionMessageList);
                }
                QuestionnaireMessage save = questionnaireMessageRepository.save(q);
                for (OptionMessage option : optionMessageList) {
                    OptionMessage optionMessage = new OptionMessage();
                    optionMessage.setIsDel(0);
                    optionMessage.setQuestionnaireName(save.getQuestionnaireName());
                    optionMessage.setQuestionnaireMessageId(save.getId());
                    optionMessage.setCreateTime(new Date());
                    optionMessage.setOptionName(option.getOptionName());
                    optionMessage.setCorrectAnswer(option.getCorrectAnswer());
                    optionMessageRepository.save(optionMessage);
                }
            }
        });
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "添加成功", null);
    }

    @Override
    public ResultInfo getQuestionnaireMessage(String activityId) {
        List<QuestionnaireMessageDto> resultInfoList = new ArrayList<>();
        List<QuestionnaireMessage> byIsDel = questionnaireMessageRepository.findByIsDelAndActivityInfoId(0, Integer.valueOf(activityId));
        ActivityRule byActivityInfoId = activityRuleRepository.findByActivityInfoId(Integer.valueOf(activityId));
        Optional<ActivityInfo> byId = activityInfoRepository.findById(Integer.valueOf(activityId));
        List<String> prizeStateList = new ArrayList<>();
        for (QuestionnaireMessage questionnaireMessage : byIsDel) {
            QuestionnaireMessageDto q = new QuestionnaireMessageDto();
            q.setId(questionnaireMessage.getId());
            q.setIsDel(questionnaireMessage.getIsDel());
            q.setIsRandom(questionnaireMessage.getIsRandom());
            q.setIsSingle(questionnaireMessage.getIsSingle());
            q.setMustAnswer(questionnaireMessage.getMustAnswer());
            q.setQuestionnaireName(questionnaireMessage.getQuestionnaireName());
            if (byActivityInfoId != null) {
                q.setSave_message(byActivityInfoId.isSaveMessage());
                q.setShow_message(byActivityInfoId.isShowMessage());
            }
            List<OptionMessage> allByQuestionnaireMessageId = optionMessageRepository.findAllByQuestionnaireMessageIdAndIsDel(questionnaireMessage.getId(), 0);
            q.setOptionMessageList(allByQuestionnaireMessageId);
            q.setDescriptionMessage(byId.get().getDescription());
            q.setPrizeStateList(prizeStateList);
            resultInfoList.add(q);
        }
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "查询成功", resultInfoList);
    }

    @Override
    public ResultInfo saveMessage(List<Object> messageList, List<Object> optionList, Integer activityId) {
        List<QuestionnaireMessage> byIsDelAndActivityInfoId = questionnaireMessageRepository.findByIsDelAndActivityInfoId(0, activityId);
        if (CollectionUtils.isNotEmpty(byIsDelAndActivityInfoId)) {
            for (QuestionnaireMessage questionnaireMessage : byIsDelAndActivityInfoId) {
                questionnaireMessage.setIsDel(1);
                questionnaireMessageRepository.save(questionnaireMessage);
            }
        }
        List<QuestionnaireMessage> list = new ArrayList<>();
        for (Object o : messageList) {
            QuestionnaireMessage copyMessage = new QuestionnaireMessage();
            BeanUtils.copyProperties(o, copyMessage);
            QuestionnaireMessage message = new QuestionnaireMessage();
            message.setIsDel(0);
            message.setIsShow(0);
            message.setActivityInfoId(activityId);
            message.setIsSingle(copyMessage.getIsSingle());
            message.setIsRandom(copyMessage.getIsRandom());
            message.setMustAnswer(copyMessage.getMustAnswer());
            message.setCreateTime(new Date());
            message.setQuestionnaireName(copyMessage.getQuestionnaireName());
            message.setType("daily");
            message.setYesterdayShow(0);
            QuestionnaireMessage save = questionnaireMessageRepository.save(message);
            list.add(save);
        }
        for (Object o : optionList) {
            OptionMessage copyOption = new OptionMessage();
            BeanUtils.copyProperties(o, copyOption);
            OptionMessage message = new OptionMessage();
            message.setIsDel(copyOption.getIsDel());
            message.setCorrectAnswer(copyOption.getCorrectAnswer());
            message.setCreateTime(new Date());
            message.setOptionName(copyOption.getOptionName());
            message.setQuestionnaireName(copyOption.getQuestionnaireName());
            for (QuestionnaireMessage questionnaireMessage : list) {
                if (copyOption.getQuestionnaireName().equals(questionnaireMessage.getQuestionnaireName())) {
                    message.setQuestionnaireMessageId(questionnaireMessage.getId());
                }
            }
            optionMessageRepository.save(message);
        }
        Collections.shuffle(list);
        ActivityRule byActivityInfoId = activityRuleRepository.findByActivityInfoId(activityId);
        Integer countNum = byActivityInfoId.getCountNum();
        for (int i = 0; i < countNum; i++) {
            QuestionnaireMessage message = list.get(i);
            message.setYesterdayShow(1);
            message.setIsShow(1);
            questionnaireMessageRepository.save(message);
        }
        return new ResultInfo("SUCCESS", "保存成功", null);
    }

    @Override
    public List<Object> getDailyMessage(Integer activityInfoId, int pageNum, int pageSize) {
        int pageCount = pageNum * pageSize;
        List<Object> returnList = new ArrayList<>();
        List<Integer> idList = new ArrayList<>();
        List<Long> idList1 = new ArrayList<>();
        List<QuestionnaireMessage> daily = new ArrayList<>();
        long allByCount = 0L;

        ActivityConsoleUser principal = this.getPrincipal();
        String authoritiesStr = principal.getAuthoritiesStr();
        if (authoritiesStr.equals("ROLE_USER_SELF")) {
            String username = principal.getUsername();
            List<ActivityInfo> byCreateBy = activityInfoRepository.findByCreateByAndTypeIdentification(username, "daily");
            for (ActivityInfo activityInfo : byCreateBy) {
                idList.add(activityInfo.getId());
            }
            daily = questionnaireMessageRepository.findAllByByUser(activityInfoId, "daily", idList, pageCount, pageSize);
            allByCount = questionnaireMessageRepository.findAllByCountAndUser(activityInfoId, "daily", idList);
        } else {
            daily = questionnaireMessageRepository.findAllBy(activityInfoId, "daily", pageCount, pageSize);
            allByCount = questionnaireMessageRepository.findAllByCount(activityInfoId, "daily");
            for (QuestionnaireMessage message : daily) {
                idList.add(message.getId().intValue());
            }
        }
        List<ActivityInfo> name = activityInfoRepository.findByTypeIdentificationAndState("daily", 0);
        for (Integer integer : idList) {
            idList1.add(Long.valueOf(integer));
        }
        List<OptionMessage> allBy = optionMessageRepository.findAllByQuestionnaireMessageIdInAndIsDel(idList1, 0);
        for (QuestionnaireMessage message : daily) {
            DailyMessageDto dto = new DailyMessageDto();
            dto.setQuestionnaireName(message.getQuestionnaireName());
            dto.setId(message.getId());
            dto.setCreateTime(message.getCreateTime());
            for (ActivityInfo activityInfo : name) {
                if (activityInfo.getId().equals(message.getActivityInfoId()))
                    dto.setActivityName(activityInfo.getTitle());
            }
            List<OptionMessage> optionMessageList = new ArrayList<>();
            for (OptionMessage optionMessage : allBy) {
                if (optionMessage.getQuestionnaireMessageId().equals(message.getId())) {
                    optionMessageList.add(optionMessage);
                }
            }
            dto.setOptionMessageList(optionMessageList);
            returnList.add(dto);
        }
        returnList.add(allByCount);
        return returnList;
    }

    @Override
    public ResultInfo getDailyActivityName() {
        List<ActivityInfo> returnList = new ArrayList<>();
        ActivityConsoleUser principal = this.getPrincipal();
        String authoritiesStr = principal.getAuthoritiesStr();
        if (authoritiesStr.equals("ROLE_USER_SELF")) {
            String username = principal.getUsername();
            List<ActivityInfo> byCreateBy = activityInfoRepository.findByCreateByAndTypeIdentification(username, "daily");
            returnList.addAll(byCreateBy);
            return new ResultInfo("SUCCESS", "查询成功", returnList);
        } else {
            List<Integer> daily = questionnaireMessageRepository.findAllActivityName("daily");
            List<ActivityInfo> byIdIn = activityInfoRepository.findByIdIn(daily);
            returnList.addAll(byIdIn);
            return new ResultInfo("SUCCESS", "查询成功", returnList);
        }
    }

    @Override
    public ResultInfo getInputMessage(Integer activityId, int pageNum, int pageSize) {
        List<QuestionnaireMessage> byIsDelAndActivityInfoId = questionnaireMessageRepository.findByIsDelAndActivityInfoId(0, activityId);
        List<Long> idList = new ArrayList<>();
        for (QuestionnaireMessage message : byIsDelAndActivityInfoId) {
            idList.add(message.getId());
        }
        List<OptionMessage> allBy = optionMessageRepository.findAllByQuestionnaireMessageIdInAndIsDel(idList, 0);
        for (OptionMessage optionMessage : allBy) {

        }
        return null;
    }

    @Override
    public List<QuestionnaireMessage> getQuestionnaire(String activityId) {
        List<QuestionnaireMessage> byIsDelAndActivityInfoId = questionnaireMessageRepository.findByIsDelAndActivityInfoId(0, Integer.valueOf(activityId));
        return byIsDelAndActivityInfoId;
    }

    @Override
    public HashMap<String, List<String>> getOption(List<QuestionnaireMessage> questionnaire) {
        HashMap<String, List<String>> returnMap = new HashMap<>();
        String time = "";
        for (QuestionnaireMessage questionnaireMessage : questionnaire) {
            List<String> timeList = new ArrayList<>();
            List<String> returnList = new ArrayList<>();
            List<QuestionnaireAnswersMessage> answersMessages = questionnaireAnswersMessageRepository.findByQuestionnaireMessageIdOrderByCreateTimeDesc(questionnaireMessage.getId().intValue());
            for (QuestionnaireAnswersMessage answersMessage : answersMessages) {
                if (StringUtils.isNotBlank(answersMessage.getAnswersMessage())) {
                    returnList.add(answersMessage.getAnswersMessage());
                    time = answersMessage.getCreateTime().toString().substring(0, 19);
                    timeList.add(time);
                } else {
                    Optional<OptionMessage> byId = optionMessageRepository.findById(Long.valueOf(answersMessage.getOptionMessageId()));
                    OptionMessage optionMessage = byId.get();
                    returnList.add(optionMessage.getOptionName());
                    time = answersMessage.getCreateTime().toString().substring(0, 19);
                    timeList.add(time);
                }
            }
            returnMap.put(questionnaireMessage.getQuestionnaireName() + "", returnList);
            returnMap.put("提交时间", timeList);
        }
        return returnMap;
    }

    /*
     *PostAuthorize 已经支持EL 表达式
     */
    @RequestMapping(value = "/getPrincipal", method = RequestMethod.GET)
    @PostAuthorize(" returnObject!=null && returnObject.authoritiesStr == authentication.name ")
    public ActivityConsoleUser getPrincipal() {
        Object pricipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ActivityConsoleUser activityConsoleUser;
        if (pricipal instanceof ActivityConsoleUser) {
            activityConsoleUser = (ActivityConsoleUser) pricipal;
        } else {
            activityConsoleUser = null;
        }
        return activityConsoleUser;
    }
}
